/*
 * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license
 * distributed with this file and available online at
 * http://www.ja-sig.org/products/cas/overview/license/
 */
package org.jasig.cas.adaptors.jdbc;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.validation.constraints.NotNull;

import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.springframework.dao.IncorrectResultSizeDataAccessException;

/**
 * Class that if provided a query that returns a password (parameter of query
 * must be username) will compare that password to a translated version of the
 * password provided by the user. If they match, then authentication succeeds.
 * Default password translator is plaintext translator.
 * 
 * @author Scott Battaglia
 * @author Dmitriy Kopylenko
 * @version $Revision$ $Date$
 * @since 3.0
 */
public class QueryDatabaseAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {

    @NotNull
    private String sql;

    protected final boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials) throws AuthenticationException {
    	final String username = getPrincipalNameTransformer().transform(credentials.getUsername());
    	/*
    	 * lgw 2016-11-16
    	 * 判断用户是否锁定
    	 * 0：锁定 true   1：正常 false
    	 * 当用户密码验证通过后，我会把用户名后添加固定后缀_#$_state，通过后缀来区分是否是要验证用户状态
    	 * 
    	 */
    	if(username.contains("_#$_state")){
    		String un = username.substring(0,username.length()-9);
    		try {
				credentials.setUsername(URLEncoder.encode(un, "UTF-8"));//chenBQ 20171122 对登录的用户名进行UTF-8编码，处理中文无法登录
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
    		String stateSql = "select state from pure_user where lower(login_id)=lower(?)";
    		final Integer state = getJdbcTemplate().queryForObject(stateSql, Integer.class, un);
    		System.out.println("======query=state====="+state);
    		return 0==state;
    	}else{
	        final String password = credentials.getPassword();
	        final String encryptedPassword = this.getPasswordEncoder().encode(
	            password);
	        
	        try {
	            final String dbPassword = getJdbcTemplate().queryForObject(this.sql, String.class, username);
	            return dbPassword.equals(encryptedPassword);
	        } catch (final IncorrectResultSizeDataAccessException e) {
	            // this means the username was not found.
	            return false;
	        }
    	}
    }

    /**
     * @param sql The sql to set.
     */
    public void setSql(final String sql) {
        this.sql = sql;
    }
}